import sx126x, aead, binascii
from machine import SPI
from pyb import Pin, ExtInt, LED
import utime, urandom

# poweron
PowerPin = Pin('B10', Pin.OUT_PP)
PowerPin.on()

utime.sleep(1)

spi = SPI(2)
spi.init(baudrate=10000000)

sx126x.Init(spi, rst='A15', nss='B12', busy='B4')
sx126x.Begin(freq=434000000, power=22)

callback = lambda e: LED(1).toggle()

ExtInt(Pin('B3'), ExtInt.IRQ_RISING, Pin.PULL_NONE, callback)

# const unsigned char key[32] = {
# 		0xf9, 0xd7, 0xde, 0xe9, 0xa9, 0xcb, 0xbd, 0xec, 0xbf, 0xf8, 0x8a, 0xa7, 0x78, 0xb5, 0x99, 0xb2,
# 		0x8c, 0x1a, 0xdf, 0xd6, 0x26, 0x28, 0x92, 0x3a, 0xae, 0xe4, 0x76, 0xc5, 0xec, 0x2f, 0x38, 0x1c
# };

key = b'\xf9\xd7\xde\xe9\xa9\xcb\xbd\xec\xbf\xf8\x8a\xa7\x78\xb5\x99\xb2\x8c\x1a\xdf\xd6\x26\x28\x92\x3a\xae\xe4\x76\xc5\xec\x2f\x38\x1c'

# const unsigned char ad[12] = {
# 		0xce, 0x86, 0x81, 0x95, 0x3d, 0x44, 0x63, 0x51, 0xac, 0xb8, 0x45, 0x39
# };
ad = b'\xce\x86\x81\x95\x3d\x44\x63\x51\xac\xb8\x45\x39'

aead.init(key, ad)

no = 0


tag = bytearray(16)




while True:
	data = bytearray()
	data.append(0)
	data.append(no)
	data.append(100)		#rssi
	data.append(9)			#snr

	r = bytearray(8)
	for i in range(8):
		r[i] = urandom.randrange(0, 255)
	aead.encrypt(data, r, tag)

	print(binascii.hexlify(tag))
	print(binascii.hexlify(data))


	packData = bytearray()
	packData = b'\x01'
	packData += b'\x00'
	packData += r
	packData += tag
	packData += data

	no += 1
	no = no & 0xFF

	sx126x.Send(packData, 0xFFFF)

	# wait for TX done
	while True:
		utime.sleep_ms(1)
		irqStatus = sx126x.GetIrqStatus()
		if ((irqStatus & sx126x.IRQ_TX_DONE) == sx126x.IRQ_TX_DONE):
			break

	print("SetRx")

	# RX
	sx126x.SetRx(3200, True)		# Timeout 50ms

	# wait for RX Done	
	while True:
		utime.sleep_ms(1)
		irqStatus = sx126x.GetIrqStatus()
		# print(hex(irqStatus))
		if ((irqStatus & sx126x.IRQ_RX_TX_TIMEOUT) == sx126x.IRQ_RX_TX_TIMEOUT):
			print('Timeout')
			break

		if ((irqStatus & sx126x.IRQ_RX_DONE) == sx126x.IRQ_RX_DONE):
			recvData = sx126x.Recv()
			print(binascii.hexlify(recvData))
			break

	utime.sleep(2)




